#include "../Client/Client.h"

void ClientAPI()
{
  //加载Windows环境
  WORD ver = MAKEWORD(2, 2);
  WSADATA dat;
  WSAStartup(ver, &dat);

  //创建socket
  SOCKET Client_sock = socket(AF_INET, SOCK_STREAM, 0);
  if (INVALID_SOCKET == Client_sock) {
    printf("Build client's socket failed!!!\n");
  }
  else {
    printf("Build client's socket successful...\n");
  }
  //
  sockaddr_in Server_sin = {};
  Server_sin.sin_family = AF_INET;
  Server_sin.sin_port = htons(SERVER_PORT);
  //Server_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //INADDR_ANY为默认IP
  //将十进制SERVER_IP转化为二进制保存至Server_sin.sin_addr中
  inet_pton(AF_INET, SERVER_IP, &Server_sin.sin_addr);

  //调用connect函数连接服务端
  int connectRet = connect(Client_sock, (sockaddr*)&Server_sin, sizeof(sockaddr_in));
  if (INVALID_SOCKET == connectRet) {
    printf("Connect failed!!!\n");
  }
  else {
    printf("Connect successfully...\n");
  }

  //缓冲区
  while (true) {
    //输入发送信息
    DataPackage dp;
    scanf_s("%d",&dp.dealMode);
    //输入exit，表示结束
    if (dp.dealMode==-1) {
      break;
    }
    else {
      scanf_s("%s", dp.str,32);
      dp.str[strlen(dp.str)] = '\0';
      //调用send函数，将缓冲区内的数据发送至服务端
      send(Client_sock, (const char*)&dp, sizeof(DataPackage), 0);
    }
    //初始化接收缓冲区，调用recv函数进行数据接收
    char recvBuf[1024] = {};
    int nlen = recv(Client_sock, recvBuf, 127, 0);
    if (nlen > 0) {
        printf("Recv message successfully...\n");
        printf("Message:%s\n", recvBuf);
    }
    memset(recvBuf, 0, sizeof(recvBuf));
  }

  //关闭客户端连接
  closesocket(Client_sock);
  //
  WSACleanup();
  printf("Client closed...");
  getchar();
}